using System;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UIElements;
using static UnityEditor.Experimental.GraphView.Port;

namespace Framework.Fsm
{
    public class FsmEventItem : GraphElement
    {
        public FsmUserData Data { get; private set; }
        public string EventName { get { return title_input.value.Trim(); } }
        public FsmStateNode Node { get; private set; }
        public Port Port { get; private set; }
        public bool Enabled { get; private set; }
        private TextField title_input;
        public FsmEventItem(FsmStateNode stateNode)
        {
            Data = new FsmUserData() { Id = Guid.NewGuid().ToString(), DataType = UserDataType.Event, Target = this };
            Node = stateNode;
            styleSheets.Add(Resources.Load<StyleSheet>("FsmEventItem"));
            this.style.flexDirection = FlexDirection.RowReverse;
            title_input = new TextField()
            {
                value = "Finished"
            };
            title_input.RegisterValueChangedCallback(evt =>
            {
                Node.onEventNameChanged(this);
            });
            var deleteButton = new Button(() =>
            {
                Node.RemoveEvent(this);
            })
            {
                text = "X"
            };
            Port = Port.Create<Edge>(Orientation.Horizontal, Direction.Output, Capacity.Single, typeof(Port));
            Port.userData = Data;
            Port.portName = "";
            this.contentContainer.Add(Port);
            this.contentContainer.Add(title_input);
            this.contentContainer.Add(deleteButton);
        }
        public void SetError(bool value)
        {
            Enabled = !value;
            Port.style.backgroundColor = new StyleColor(new Color(1f, 0f, 0f, value ? 1f : 0f));
        }
        public void SetName(string name)
        {
            title_input.value = name;
        }
    }
}